package com.tanhua.server.controller;

import com.tanhua.commons.aliyun.utils.AliyunOssUtils;
import com.tanhua.commons.utils.FileUtils;
import com.tanhua.domain.vo.PicUploadResult;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RequestMapping("pic/upload")
@Controller
public class PicUploadController {

    @Autowired
    private AliyunOssUtils ossUtils;

    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
            ".jpeg", ".gif", ".png"};

    @PostMapping
    @ResponseBody
    public PicUploadResult upload(MultipartFile file) throws IOException {

        String fileName = file.getOriginalFilename();

        String fileFormat = StringUtils.substringAfter(fileName,".");

        if(!ArrayUtils.contains(IMAGE_TYPE, fileFormat)) {
            return PicUploadResult.error();
        }

        String filePath = FileUtils.getFilePath(fileFormat);

        String imageUrl = ossUtils.upload(filePath, file.getInputStream());

        return PicUploadResult.ok(imageUrl);
    }
}
